<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row v-show="showSearch">
				<el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList" :rules="dataRules">
					<el-form-item prop="siteId" label="企业">
						<el-select v-model="state.queryForm.siteId" @change="handleChangeSite" filterable>
							<el-option v-for="item in siteList" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="monitorEquipmentId" label="设备">
						<el-select v-model="state.queryForm.monitorEquipmentId" @change="handleChangeEquipment" filterable>
							<el-option v-for="item in equitpmentList" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="factorIdList" label="检测因子">
						<el-select v-model="state.queryForm.factorIdList" multiple collapse-tags collapse-tags-tooltip>
							<el-option v-for="item in divisorList" :key="item.id" :label="item.cnName" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="eventStatus" label="处理状态">
						<el-select v-model="state.queryForm.eventStatus">
							<el-option label="未处理" :value="10" />
							<el-option label="已处理" :value="20" />
							<el-option label="误报" :value="30" />
						</el-select>
					</el-form-item>
					<el-form-item prop="dateTime" label="起止时间">
						<el-date-picker
							v-model="state.queryForm.dateTime"
							type="datetimerange"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							value-format="YYYY-MM-DD HH:mm:ss"
						/>
					</el-form-item>
					<el-form-item>
						<el-button icon="search" type="primary" @click="handleSubmit">查询</el-button>
						<el-button icon="Refresh" @click="resetQuery">重置</el-button>
					</el-form-item>
				</el-form>
			</el-row>
			<el-row>
				<div class="mb8" style="width: 100%">
					<!-- <el-button plain :disabled="multiple" icon="Delete" type="danger" v-auth="'platform_alarmLogging_del'" @click="handleDelete(selectObjs)">
						删除
					</el-button> -->
					<right-toolbar
						v-model:showSearch="showSearch"
						:export="'platform_alarmLogging_export'"
						@exportExcel="exportExcel"
						class="ml10 mr20"
						style="float: right"
						@queryTable="getDataList"
					></right-toolbar>
				</div>
			</el-row>
			<el-table
				:data="state.dataList"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				@selection-change="handleSelectionChange"
				@sort-change="sortChangeHandle"
			>
				<!-- <el-table-column type="selection" width="40" align="center" /> -->
				<el-table-column prop="equipmentCode" label="设备编码" show-overflow-tooltip />
				<el-table-column prop="equipmentName" label="设备名称" show-overflow-tooltip />
				<el-table-column prop="address" label="安装点" show-overflow-tooltip />
				<el-table-column prop="cnName" label="监测因子" show-overflow-tooltip />
				<el-table-column prop="currentValue" label="当前值" show-overflow-tooltip />
				<el-table-column prop="alarmCauses" label="报警内容" show-overflow-tooltip min-width="180" />
				<el-table-column prop="createTime" label="报警时间" show-overflow-tooltip width="160" sortable="custom" />
				<el-table-column prop="updateTime" label="报警恢复时间" show-overflow-tooltip width="160" sortable="custom" />
				<el-table-column prop="eventStatus" width="110" label="处理状态" show-overflow-tooltip sortable="custom">
					<template #default="scope">
						<el-tag :type="scope.row.eventStatus === 20 ? 'success' : scope.row.eventStatus === 10 ? 'warning' : 'info'">{{
							scope.row.eventStatus === 20 ? '已处理' : scope.row.eventStatus === 10 ? '未处理' : '误报'
						}}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="150" fixed="right">
					<template #default="scope">
						<!-- <el-button icon="edit-pen" text type="primary" v-auth="'platform_alarmLogging_edit'" @click="formDialogRef.openDialog(scope.row.id)"
							>编辑</el-button
						> -->
						<el-button
							text
							icon="remove"
							type="info"
							v-if="scope.row.eventStatus === 10"
							v-auth="'platform_alarmLogging_del'"
							@click="handleStatus(scope.row.id, 30)"
							>误报</el-button
						>
						<el-button
							text
							type="success"
							icon="check"
							v-if="scope.row.eventStatus === 10"
							v-auth="'platform_alarmLogging_del'"
							@click="handleStatus(scope.row.id, 20)"
							>已处理</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>
	</div>
</template>

<script setup lang="ts" name="systemAlarmLogging">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs, putObj } from '/@/api/platform/alarmLogging';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { fetchListAll as fetchSiteList } from '/@/api/platform/airSite';
import { fetchListAll as fetchEquipmentList } from '/@/api/platform/airMonitorEquipment';
import { fetchFactorDetailList as fetchDataTemplateList } from '/@/api/platform/dataTemplate';
import { useAlarm } from '/@/stores/alarm';
import { useRoute } from 'vue-router';
// 定义查询字典

// 定义变量内容
const formDialogRef = ref();
const route = useRoute();
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);
const siteList: any = ref([]);
const divisorList: any = ref([]);
const equitpmentList: any = ref([]);
const routeQuery = reactive({ equipmentId: null, siteId: null });

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		siteId: null,
		monitorEquipmentId: null,
		factorIdList: [],
		dateTime: [],
	},
	createdIsNeed: false,
	pageList: fetchList,
	descs: ['create_time'],
});
// 定义校验规则
const dataRules = ref({
	// siteId: [{ required: true, message: '请选择', trigger: 'change' }],
	// monitorEquipmentId: [{ required: true, message: '请选择', trigger: 'change' }],
	// factorIdList: [{ required: true, message: '请选择', trigger: 'change' }],
	// type: [{ required: true, message: '请选择', trigger: 'change' }],
	// dateTime: [{ required: true, message: '请选择', trigger: 'change' }],
});
//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	getDataList();
};
// 查询
const handleSubmit = async () => {
	const valid = await queryRef.value.validate();
	if (!valid) return false;
	getDataList();
};
// 导出excel
const exportExcel = () => {
	downBlobFile('/platform/alarmLogging/export', state.queryForm, 'alarmLogging.xlsx');
};

// 多选事件
const handleSelectionChange = (objs: { id: string }[]) => {
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm('确定修改该条警报状态吗？');
	} catch {
		return;
	}

	try {
		await delObjs(ids);
		getDataList(false);
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
const handleChangeSite = (e) => {
	getEquipment(e);
};
const handleChangeEquipment = (e) => {
	state.queryForm.factorIdList = [];
	const item = equitpmentList.value.find((d) => d.id === e);
	getDivisor(item.dataTemplateId);
};
const getSites = () => {
	fetchSiteList().then((res) => {
		siteList.value = res.data;
	});
};
const getDivisor = (dataTemplateId: string) => {
	fetchDataTemplateList({ id: dataTemplateId }).then((res) => {
		const l = res.data[0];
		l && (divisorList.value = res.data);
	});
};
const getEquipment = (siteId: string) => {
	state.queryForm.monitorEquipmentId = '';
	fetchEquipmentList({ airSiteId: siteId }).then((res) => {
		equitpmentList.value = res.data;
	});
};
const handleStatus = async (id: string, eventStatus: number) => {
	try {
		await useMessageBox().confirm('确定要修改该条报警状态吗？');
	} catch {
		return;
	}

	try {
		await putObj({ id, eventStatus });
		getDataList(false);
		useMessage().success('修改成功');
		setAlarmCount();
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
const setAlarmCount = async () => {
	const res = await fetchList({ eventStatus: 10, descs: 'create_time' });
	useAlarm().setAlarmCount(res.data.total || 0);
};
onMounted(() => {
	const route_query = route.query;
	Object.assign(routeQuery, route_query);
	getSites();
	if (route_query?.siteId) {
		state.queryForm.siteId = route_query.siteId;
		getEquipment(route_query.siteId as string);
		state.ascs = ['event_status'];
		state.descs = [];
		state.queryForm.monitorEquipmentId = route_query.equipmentId;
	}
	getDataList();
});
</script>
